package com.iraeta.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.ServiceException;
import com.iraeta.entity.BussDanJu;
import com.iraeta.entity.Cbtest;
import com.iraeta.service.BpmMakeDateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController(value = "BpmMakeDateController")
@RequestMapping("bpmmakedate")
public class BpmMakeDateController extends BaseController{
    @Autowired
    BpmMakeDateService service;

    /*
     * 获取所有的业务
     * */
    @RequestMapping("getallcbtest")
    public String getAllCbTest(){
        List<Cbtest> cbtestList = service.listCbTest();
        return this.success(cbtestList);
    }

    /*
     * 根据业务类型和关键字查询前10条的业务单据
     * */
    @RequestMapping("getbussdanju")
    public String getBussDanJu(@RequestBody JSONObject jo){
        int bussid = jo.getIntValue("bussid");
        Cbtest cbtest = service.getCbTest(bussid);
        if(cbtest == null){
            throw new ServiceException("请选择单据业务类型");
        }
        String key1 = jo.getString("key1");
        List<BussDanJu> bussDanJuList = service.listBussDanJu(cbtest.getTableName(), cbtest.getDhName(), key1);
        for (BussDanJu bussDanJu : bussDanJuList) {
            bussDanJu.setdDateStr(DateUtil.format(bussDanJu.getdDate(), DatePattern.NORM_DATE_PATTERN));
        }
        return this.success(bussDanJuList);
    }

    /*
     * 根据业务类型和关键字查询前10条的业务单据
     * */
    @RequestMapping("updatedanjuddate")
    public String updateDanJuDdate(@RequestBody JSONObject jo){
        long iid = jo.getLongValue("iid");
        if(iid == 0){
            throw new ServiceException("IID参数不正确");
        }
        String dDate = jo.getString("dDate");
        if(StrUtil.isEmpty(dDate)){
            throw new ServiceException("制单日期参数不正确");
        }

        int bussid = jo.getIntValue("bussid");
        Cbtest cbtest = service.getCbTest(bussid);
        if(cbtest == null){
            throw new ServiceException("请选择单据业务类型");
        }
        service.updateBussDanJuDDate(cbtest.getTableName(), iid, dDate);
        return this.success();
    }
}
